package com.yhq.ojbackendjudgeservice.client;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

import com.yhq.ojbackendcommon.common.ErrorCode;
import com.yhq.ojbackendcommon.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import com.yhq.ojbackendmodel.model.codesandbox.ExcuteCodeRequest;
import com.yhq.ojbackendmodel.model.codesandbox.ExcuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

import static com.yhq.ojbackendcommon.utils.SignUtils.genSign;


@Slf4j
public class CodeSandboxClient {
    public static final String GATEWAY_HOST = "http://localhost:8090";
    private final String authRequestHeader;
    private final String secretKey;
    public CodeSandboxClient(String authRequestHeader, String secretKey){
        this.authRequestHeader = authRequestHeader;
        this.secretKey = secretKey;
    }

    public ExcuteCodeResponse executeCode(ExcuteCodeRequest executeCodeRequest) {
        try {
            String json = JSONUtil.toJsonStr(executeCodeRequest);
            String sign = genSign(json, secretKey);
//            System.out.println(json);
            String httpResponse = HttpUtil.createPost(GATEWAY_HOST+"/execute")
                    .header("Content-Type", "application/json")
                    .header(authRequestHeader,sign)
                    .body(json)
                    .execute()
                    .body();
            if(StringUtils.isBlank(httpResponse)){
                throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteCodesanbox error"+ httpResponse);
            }
            return JSONUtil.toBean(httpResponse, ExcuteCodeResponse.class);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("在执行将请求参数转为JSON字符串时出错");
            return null;
        }
    }
}